package org.example;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class MainClass {
    public static void main(String[] args) throws SQLException {
//        delStudent();
//        updateStudent();
//        addStudent();
        findStudent();
        System.out.println(JDBCUtils.getDataSource());
    }

    /**
     * 查找
     */
    public static void findStudent() throws SQLException {
//        Connection con = JDBCUtils.getCon();
        Connection con = JDBCUtils.getConn();
        String sql = "select * from t_student";
        PreparedStatement ps = con.prepareStatement(sql); //创建预编译对象，执行sql语句，处理结果
        ResultSet rs = ps.executeQuery(); //用于查
        //封装学生对象
        Student stu = null;
        ArrayList<Object> list = new ArrayList<>();
        while (rs.next()) {
            stu = new Student();
            // 数据的封装：将数据表中的字段与Java对象的属性，一一对应。将数据表——》一个Java类，一行数据——》一个对象，一个字段——》属性。ORM关系映射
            System.out.print("学生姓名：" + rs.getString("student_name") + "==");
            System.out.println("学生年龄：" + rs.getInt("student_age"));
            System.out.println("学生id：" + rs.getInt("id"));
            stu.setName(rs.getString("student_name"));
            stu.setAge(rs.getInt("student_age"));
            stu.setId(rs.getInt("id"));
            list.add(stu);
        }
        System.out.println("查询学生列表：" + list);
    }

    /**
     * 增加
     *
     * @throws SQLException
     */
    public static void addStudent() throws SQLException {
        Connection con = JDBCUtil.getCon();
        String sql = "insert into t_student(student_name,student_age) values(?,?)";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setString(1, "小米");
        ps.setInt(2, 20);
        //执行sql
        int i = ps.executeUpdate(); //用于增删改
        System.out.println(i > 0 ? "添加学生成功" : "添加失败");
    }

    /**
     * 修改
     *
     * @throws SQLException
     */
    public static void updateStudent() throws SQLException {
        Connection con = JDBCUtil.getCon();
        String sql = "update t_student set student_name = ?, student_age = ? where id = ?";
        PreparedStatement ps = con.prepareStatement(sql);
        ps.setInt(3, 6); //修改id为6的数据
        ps.setString(1, "张三");
        ps.setInt(2, 60);
        //执行sql
        int i = ps.executeUpdate();
        System.out.println(i > 0 ? "更新学生成功" : "更新失败");

    }

    /**
     * 删除
     */
    public static void delStudent() {
        //删除学生
        try {
            Connection con = JDBCUtil.getCon();
            String sql = "delete from t_student where id =?";
            PreparedStatement ps = con.prepareStatement(sql);
            ps.setInt(1, 7); //删除id为7的行
            int i = ps.executeUpdate();
            System.out.println(i > 0 ? "删除学生成功" : "删除失败");
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}
